﻿//--------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// This source code is intended only as a supplement to Microsoft
// Development Tools and/or on-line documentation.  See these other
// materials for detailed information regarding Microsoft code samples.
// 
// THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//--------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml.Linq;
using SharePoint.Silverlight.Map.SharePointOnlineListsService;
using System.Windows.Browser;

namespace SharePoint.Silverlight.Map
{
    public partial class Page : UserControl
    {
        public Page(IDictionary<string, string> parms)
        {
           
            InitializeComponent();
            //Initialize properties:

            //sets the title of the silverlight control
            if (parms.Keys.Contains(titleParam))
            {
                _title.Text = parms[titleParam];
                _title.FontSize = 36;
            }
            //title column of list - used in tooltip
            if (parms.Keys.Contains(titleColumnParam))
            {
                _titleColumn = parms[titleColumnParam];

            }
            //if the description column is an Image - set a template for showing the image
            //in the tooltip
            if (parms.Keys.Contains(descriptionIsImageParam))
            {
                _descriptionTemplate = "<a  target=\"_new\" href=\"{0}\"><img src=\"{1}\" alt=\"{2}\"/></a>";
                _descriptionIsImage = true;
            }
            //description information
            _descriptionColumn = SafeRead(parms, descriptionColumnParam, _descriptionColumn);

            //name of the list to read data from
            _listName = parms[listParam];
            //column in _listName that contains latitude information
            _latColumn = parms[latColumn];
            //column in _listName that contains longitude information
            _longColumn = parms[longColumn];
            //pin color - defaults to green
            _pinColor = SafeRead(parms, pinColorParam, _pinColor);
            string uri = null;
            //build up the URI for the Lists.asmx service dynamically
            string scheme = HtmlPage.Document.DocumentUri.Scheme;
            //no way to know if the URI contains a subsite or just a folder name
            //need to pass this in as a paramater
            if (parms.Keys.Contains(subSiteParam))
            {
                uri = scheme + "://" + HtmlPage.Document.DocumentUri.Host + "/" + parms[subSiteParam] + "/_vti_bin/Lists.asmx";
            }
            else
                uri = scheme + "://" + HtmlPage.Document.DocumentUri.Host + "/_vti_bin/Lists.asmx";
            //use the proxy to get the data
            ListsSoapClient proxy = new ListsSoapClient("ListsSoap", uri);
            proxy.GetListItemsCompleted += new EventHandler<GetListItemsCompletedEventArgs>(proxy_GetListItemsCompleted);
            XDocument doc = XDocument.Parse("<Document><Query /><ViewFields /><QueryOptions /></Document>");
            XElement query = new XElement("Query");
            XElement viewFields = new XElement("ViewFields");
            XElement queryOptions = new XElement("QueryOptions");

            proxy.GetListItemsAsync(_listName, string.Empty,
                                    query,
                                    viewFields,
                                    "1500",
                                    queryOptions,
                                    string.Empty);
        }

        private string SafeRead(IDictionary<string, string> parms, string paramKey, string oldValue)
        {
            if (parms.Keys.Contains(paramKey))
            {
                return parms[paramKey];
            }
            return oldValue;
        }

        void proxy_GetListItemsCompleted(object sender, GetListItemsCompletedEventArgs e)
        {
            //read the data
            XElement result = e.Result;
            var items = from x in result.Elements().First().Elements()
                        select new { Title = MakeName(x), Description = MakeDescription(x), Long = x.Attribute("ows_" + _longColumn).Value, Lat = x.Attribute("ows_" + _latColumn).Value };
            //iterate through each item
            foreach (var item in items)
            {
                //call out to MyMap.js and the addPin method
                //adds a pin for each item, javascript uses Virtual Earth
                HtmlPage.Window.Invoke("addPin", new object[] { item.Lat, item.Long, item.Title, _pinColor, item.Description });

            }
        }

        private string MakeDescription(XElement x)
        {
            try
            {
                string val = x.Attribute("ows_" + _descriptionColumn).Value;
                if (_descriptionIsImage)
                {
                    string imgurl = x.Attribute("ows_EncodedAbsThumbnailUrl").Value;
                    string absurl = x.Attribute("ows_EncodedAbsUrl").Value;
                    return String.Format(_descriptionTemplate, absurl, imgurl, val);

                }
                else
                    return String.Format(_descriptionTemplate, val);

            }
            catch
            {
            }
            return String.Format("<div>No Description</div>");

        }
        string MakeName(XElement x)
        {
            try
            {
                string val = x.Attribute("ows_" + _titleColumn).Value;

                return val;
            }
            catch
            {
            }
            return "No title";
        }
        string _titleColumn = "Title";
        bool _descriptionIsImage = false;
        string _pinColor = "green";
        string _listName;
        string _latColumn;
        string _longColumn;
        string _descriptionColumn = "Title";
        string _descriptionTemplate = "<div>{0}</div>";
        static string descriptionIsImageParam = "descriptionIsImage";
        static string descriptionColumnParam = "descriptionColumn";
        static string titleColumnParam = "titleColumn";
        static string titleParam = "title";
        static string pinColorParam = "pinColor";
        static string listParam = "listName";
        static string latColumn = "latColumn";
        static string longColumn = "longColumn";
        static string subSiteParam = "siteUrl";


    }
}
